{********************************************************************}
{                                                                    }
{           Developer Express Visual Component Library               }
{           Express Cross Platform Library controls                  }
{                                                                    }
{           Copyright (c) 2000-2014 Developer Express Inc.           }
{           ALL RIGHTS RESERVED                                      }
{                                                                    }
{   The entire contents of this file is protected by U.S. and        }
{   International Copyright Laws. Unauthorized reproduction,         }
{   reverse-engineering, and distribution of all or any portion of   }
{   the code contained in this file is strictly prohibited and may   }
{   result in severe civil and criminal penalties and will be        }
{   prosecuted to the maximum extent possible under the law.         }
{                                                                    }
{   RESTRICTIONS                                                     }
{                                                                    }
{   THIS SOURCE CODE AND ALL RESULTING INTERMEDIATE FILES            }
{   (DCU, OBJ, DLL, ETC.) ARE CONFIDENTIAL AND PROPRIETARY TRADE     }
{   SECRETS OF DEVELOPER EXPRESS INC. THE REGISTERED DEVELOPER IS    }
{   LICENSED TO DISTRIBUTE THE EXPRESSCROSSPLATFORMLIBRARY AND ALL   }
{   ACCOMPANYING VCL CONTROLS AS PART OF AN EXECUTABLE PROGRAM       }
{   ONLY.                                                            }
{                                                                    }
{   THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED       }
{   FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE         }
{   COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE        }
{   AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT   }
{   AND PERMISSION FROM DEVELOPER EXPRESS INC.                       }
{                                                                    }
{   CONSULT THE END USER LICENSE AGREEMENT FOR INFORMATION ON        }
{   ADDITIONAL RESTRICTIONS.                                         }
{                                                                    }
{********************************************************************}

unit dxZIPUtils;

{$I cxVer.inc}

interface

uses
  Windows, Classes, SysUtils, ZLIB, RTLConsts, dxCore, dxCoreClasses, cxClasses
  {$IFDEF DELPHI12}, AnsiStrings {$ENDIF};

type
  TdxZIPCustomStream = class;

  EdxZIPUnsupportedCompressionMethod = class(EdxException);

  EdxPackedStreamReader = class(Exception);
  EdxPackedStreamWriter = class(Exception);

  { TdxZIPFileEntry }

  TdxZIPFileEntry = packed record
    Sign: Integer;
    VersionToExtract: Word;
    Flag: Word;
    Method: Word;
    DateTime: Cardinal;
    CRC32: Integer;
    PackedSize: Integer;
    OriginalSize: Integer;
    NameLength: Word;
    ExtraLength: Word;
  end;

  { TdxZIPDataDescriptor }
   
  TdxZIPDataDescriptor = packed record
    CRC32: Integer;
    PackedSize: Integer;
    OriginalSize: Integer;
  end;

  { TdxZIPCentralDirEntry }
  
  TdxZIPCentralDirEntry = packed record
    Sign: Integer;
    Version: Word;
    VersionToExtract: Word;
    Flag: Word;
    Method: Word;
    DateTime: Cardinal;
    CRC32: Integer;
    PackedSize: Integer;
    OriginalSize: Integer;
    NameLength: Word;
    ExtraLength: Word;
    CommentLength: Word;
    DiskStart: Word;
    IntAttributes: Word;
    ExtAttributes: Integer;
    RelativeOffset: Integer;
  end;

  { TdxZIPEndOfDir }

  TdxZIPEndOfDir = packed record
    Sign: Integer;
    DiskNumber: Word;
    NumberOfDiskStart: Word;
    DirStart: Word;
    DirEntryCount: Word;
    DirSize: Integer;
    DirOffset: Integer;
    CommentLength: Word;
  end;

  { TdxZIPItem }

  TdxZIPItem = class(TObject)
  private
    FData: PByte;
    FDataAssigned: Boolean;
    FName: AnsiString;
    FNameAssigned: Boolean;
    FOwner: TdxZIPCustomStream;
    FSize: Integer;

    function CheckName(const AName: AnsiString): AnsiString;

    function GetData: PByte;
    function GetIsDirectory: Boolean;
    function GetName: AnsiString;

    procedure ReadData(AStream: TStream);
    procedure ReadFileEntryData(AStream: TStream; var AData: TdxZIPFileEntry);
    procedure ReadFileName(AStream: TStream);
  protected
    FAttributes: Integer;
    FCRC32: LongWord;
    FDateTime: Cardinal;
    FPackedSize: Integer;
    FRelativeOffset: Integer;

    procedure Initialize(const ADirData: TdxZIPCentralDirEntry); overload;
    procedure Initialize(const AName: AnsiString; AData: PByte; ADataSize: Integer); overload;
    procedure Initialize(const AName: AnsiString; AStream: TStream); overload;
    procedure WriteData(AStream: TStream);
  public
    constructor Create(AOwner: TdxZIPCustomStream);
    destructor Destroy; override;
    procedure SaveTo(AStream: TStream); overload;
    procedure SaveTo(const APath: string); overload;
    //
    property Data: PByte read GetData;
    property DateTime: Cardinal read FDateTime write FDateTime;
    property Name: AnsiString read GetName;
    property Size: Integer read FSize;
    //
    property IsDirectory: Boolean read GetIsDirectory;
  end;

  { TdxZIPUnpackHelper }

  TdxZIPUnpackProc = procedure (AStream: TStream; ATargetBuffer: PByte; ATargetBufferSize: Integer) of object;

  TdxZIPUnpackHelper = class
  protected
    class procedure UnpackDeflate(ATargetBuffer: PByte; ATargetBufferSize: Integer; ASource: TStream; ASourceSize: Integer);
    class procedure UnpackNone(ATargetBuffer: PByte; ATargetBufferSize: Integer; ASource: TStream; ASourceSize: Integer);
  public
    class procedure Unpack(ACompressMethod: Word; ATargetBuffer: PByte;
      ATargetBufferSize: Integer; ASource: TStream; ASourceSize: Integer);
  end;

  { TdxZIPCustomStream }

  TdxZIPCustomStream = class(TObject)
  private
    FAutoFreeStream: Boolean;
    FItems: TcxObjectList;
    FStream: TStream;
    function GetCount: Integer;
    function GetItem(Index: Integer): TdxZIPItem;
  protected
    function Add: TdxZIPItem;
    procedure ReadItems; virtual;
    procedure WriteItems; virtual;
    //
    property Stream: TStream read FStream;
  public
    constructor Create(const AFileName: string); overload; virtual;
    constructor Create(AStream: TStream; AAutoFreeStream: Boolean = False); overload; virtual;
    destructor Destroy; override;
    //
    property Count: Integer read GetCount;
    property Items[Index: Integer]: TdxZIPItem read GetItem; default;
  end;

  { TdxZIPStreamReader }

  TdxZIPStreamReader = class(TdxZIPCustomStream)
  protected
    procedure ReadItems; override;
  public
    function Exists(const AFileName: AnsiString): Boolean;
    function Find(AFileName: AnsiString; out AItem: TdxZIPItem): Boolean;
  end;

  { TdxZIPStreamWriter }

  TdxZIPStreamWriter = class(TdxZIPCustomStream)
  protected
    procedure WriteCentralDirectory;
    procedure WriteItems; override;
  public
    constructor Create(const AFileName: string); override;
    procedure AddDirectory(const APath, ARelativeDir: AnsiString);
    procedure AddFile(const AFileName, ARelativeDir: AnsiString; AStream: TStream); overload;
    procedure AddFile(const AFileName, ARelativeDir: AnsiString; AData: PByte; ADataSize: Integer); overload;
  end;

  { TdxZIPPathHelper }

  TdxZIPPathHelper = class
  public
    class function DecodePath(const APath: AnsiString): AnsiString;
    class function EncodePath(const APath: AnsiString): AnsiString;
    class function ExcludeRootPathDelimiter(const APath: AnsiString): AnsiString;
  end;

function dxCRC32(AData: PByte; ACount: Integer): Cardinal;
implementation

const
  ZLibVersion    = $9C78;
  ZLibHeaderSize = 2;
  ZLibFooterSize = 4;

  FileHeader    = $04034B50;
  DirFileHeader = $02014B50;
  EndOfDir      = $06054B50;

  CRCTable: array[0..255] of Cardinal =
   ($00000000, $77073096, $EE0E612C, $990951BA, $076DC419, $706AF48F, $E963A535, $9E6495A3,
    $0EDB8832, $79DCB8A4, $E0D5E91E, $97D2D988, $09B64C2B, $7EB17CBD, $E7B82D07, $90BF1D91,
    $1DB71064, $6AB020F2, $F3B97148, $84BE41DE, $1ADAD47D, $6DDDE4EB, $F4D4B551, $83D385C7,
    $136C9856, $646BA8C0, $FD62F97A, $8A65C9EC, $14015C4F, $63066CD9, $FA0F3D63, $8D080DF5,
    $3B6E20C8, $4C69105E, $D56041E4, $A2677172, $3C03E4D1, $4B04D447, $D20D85FD, $A50AB56B,
    $35B5A8FA, $42B2986C, $DBBBC9D6, $ACBCF940, $32D86CE3, $45DF5C75, $DCD60DCF, $ABD13D59,
    $26D930AC, $51DE003A, $C8D75180, $BFD06116, $21B4F4B5, $56B3C423, $CFBA9599, $B8BDA50F,
    $2802B89E, $5F058808, $C60CD9B2, $B10BE924, $2F6F7C87, $58684C11, $C1611DAB, $B6662D3D,

    $76DC4190, $01DB7106, $98D220BC, $EFD5102A, $71B18589, $06B6B51F, $9FBFE4A5, $E8B8D433,
    $7807C9A2, $0F00F934, $9609A88E, $E10E9818, $7F6A0DBB, $086D3D2D, $91646C97, $E6635C01,
    $6B6B51F4, $1C6C6162, $856530D8, $F262004E, $6C0695ED, $1B01A57B, $8208F4C1, $F50FC457,
    $65B0D9C6, $12B7E950, $8BBEB8EA, $FCB9887C, $62DD1DDF, $15DA2D49, $8CD37CF3, $FBD44C65,
    $4DB26158, $3AB551CE, $A3BC0074, $D4BB30E2, $4ADFA541, $3DD895D7, $A4D1C46D, $D3D6F4FB,
    $4369E96A, $346ED9FC, $AD678846, $DA60B8D0, $44042D73, $33031DE5, $AA0A4C5F, $DD0D7CC9,
    $5005713C, $270241AA, $BE0B1010, $C90C2086, $5768B525, $206F85B3, $B966D409, $CE61E49F,
    $5EDEF90E, $29D9C998, $B0D09822, $C7D7A8B4, $59B33D17, $2EB40D81, $B7BD5C3B, $C0BA6CAD,

    $EDB88320, $9ABFB3B6, $03B6E20C, $74B1D29A, $EAD54739, $9DD277AF, $04DB2615, $73DC1683,
    $E3630B12, $94643B84, $0D6D6A3E, $7A6A5AA8, $E40ECF0B, $9309FF9D, $0A00AE27, $7D079EB1,
    $F00F9344, $8708A3D2, $1E01F268, $6906C2FE, $F762575D, $806567CB, $196C3671, $6E6B06E7,
    $FED41B76, $89D32BE0, $10DA7A5A, $67DD4ACC, $F9B9DF6F, $8EBEEFF9, $17B7BE43, $60B08ED5,
    $D6D6A3E8, $A1D1937E, $38D8C2C4, $4FDFF252, $D1BB67F1, $A6BC5767, $3FB506DD, $48B2364B,
    $D80D2BDA, $AF0A1B4C, $36034AF6, $41047A60, $DF60EFC3, $A867DF55, $316E8EEF, $4669BE79,
    $CB61B38C, $BC66831A, $256FD2A0, $5268E236, $CC0C7795, $BB0B4703, $220216B9, $5505262F,
    $C5BA3BBE, $B2BD0B28, $2BB45A92, $5CB36A04, $C2D7FFA7, $B5D0CF31, $2CD99E8B, $5BDEAE1D,

    $9B64C2B0, $EC63F226, $756AA39C, $026D930A, $9C0906A9, $EB0E363F, $72076785, $05005713,
    $95BF4A82, $E2B87A14, $7BB12BAE, $0CB61B38, $92D28E9B, $E5D5BE0D, $7CDCEFB7, $0BDBDF21,
    $86D3D2D4, $F1D4E242, $68DDB3F8, $1FDA836E, $81BE16CD, $F6B9265B, $6FB077E1, $18B74777,
    $88085AE6, $FF0F6A70, $66063BCA, $11010B5C, $8F659EFF, $F862AE69, $616BFFD3, $166CCF45,
    $A00AE278, $D70DD2EE, $4E048354, $3903B3C2, $A7672661, $D06016F7, $4969474D, $3E6E77DB,
    $AED16A4A, $D9D65ADC, $40DF0B66, $37D83BF0, $A9BCAE53, $DEBB9EC5, $47B2CF7F, $30B5FFE9,
    $BDBDF21C, $CABAC28A, $53B39330, $24B4A3A6, $BAD03605, $CDD70693, $54DE5729, $23D967BF,
    $B3667A2E, $C4614AB8, $5D681B02, $2A6F2B94, $B40BBE37, $C30C8EA1, $5A05DF1B, $2D02EF8D);

procedure CheckRead(AValue: Boolean; const AMessage: string = '');
begin
  if not AValue then
    raise EdxPackedStreamReader.Create(AMessage);
end;

function dxCRC32(AData: PByte; ACount: Integer): Cardinal;
var
  I: Integer;
begin
  Result := $FFFFFFFF;
  for I := 0 to ACount - 1 do
  begin
    Result := (Result shr 8) xor CRCTable[Byte(Result) xor AData^];
    Inc(AData);
  end;
  Result := Result xor $FFFFFFFF;
end;

{ TdxZIPItem }

constructor TdxZIPItem.Create(AOwner: TdxZIPCustomStream);
begin
  inherited Create;
  FOwner := AOwner;
  FDateTime := DateTimeToFileDate(Now);
end;

destructor TdxZIPItem.Destroy;
begin
  if FData <> nil then
  begin
    FreeMem(FData);
    FData := nil;
  end;
  inherited Destroy;
end;

procedure TdxZIPItem.SaveTo(AStream: TStream);
begin
  AStream.WriteBuffer(Data^, Size);
end;

procedure TdxZIPItem.SaveTo(const APath: string);
var
  ATargetFileName: string;
  ATargetStream: TFileStream;
begin
  ATargetFileName := IncludeTrailingPathDelimiter(APath) +
    dxAnsiStringToString(TdxZIPPathHelper.DecodePath(Name));

  if IsDirectory then
    ForceDirectories(ATargetFileName)
  else
  begin
    ForceDirectories(ExtractFilePath(ATargetFileName));
    if Size > 0 then
    begin
      ATargetStream := TFileStream.Create(ATargetFileName, fmCreate);
      try
        SaveTo(ATargetStream);
      finally
        ATargetStream.Free;
      end;
    end;
  end;
end;

procedure TdxZIPItem.Initialize(const ADirData: TdxZIPCentralDirEntry);
begin
  FAttributes := ADirData.ExtAttributes;
  FCRC32 := ADirData.CRC32;
  FDateTime := ADirData.DateTime;
  FPackedSize := ADirData.PackedSize;
  FRelativeOffset := ADirData.RelativeOffset;
  FSize := ADirData.OriginalSize;
end;

procedure TdxZIPItem.Initialize(const AName: AnsiString; AData: PByte; ADataSize: Integer);
begin
  FName := CheckName(AName);
  FNameAssigned := True;
  FDataAssigned := True;
  if AData <> nil then
  begin
    FSize := ADataSize;
    GetMem(FData, Size);
    Move(AData^, FData^, Size);
  end
  else
    FAttributes := faDirectory;
end;

procedure TdxZIPItem.Initialize(const AName: AnsiString; AStream: TStream);
begin
  FName := CheckName(AName);
  FNameAssigned := True;
  FDataAssigned := True;
  if AStream <> nil then
  begin
    FSize := AStream.Size;
    GetMem(FData, Size);
    AStream.ReadBuffer(FData^, Size);
  end
  else
    FAttributes := faDirectory;
end;

procedure TdxZIPItem.WriteData(AStream: TStream);

  procedure DoWriteData(AStream: TStream; APackedData: PByte);
  var
    AFileData: TdxZIPFileEntry;
  begin
    ZeroMemory(@AFileData, SizeOf(AFileData));
    AFileData.Sign := FileHeader;
    AFileData.VersionToExtract := 20;
    AFileData.Method := 8;
    AFileData.DateTime := DateTime;
    AFileData.CRC32 := FCRC32;
    AFileData.PackedSize := FPackedSize;
    AFileData.OriginalSize := Size;
    AFileData.NameLength := Length(FName);

    FRelativeOffset := AStream.Position;
    AStream.WriteBuffer(AFileData, SizeOf(AFileData));
    AStream.WriteBuffer(FName[1], AFileData.NameLength);
    if APackedData <> nil then
      AStream.WriteBuffer(APackedData^, FPackedSize);
  end;

var
  APackedData: PByte;
begin
  if Size > 0 then
  begin
    FCRC32 := dxCRC32(Data, Size);
  {$IFDEF DELPHI12}
    ZCompress(Data, Size, Pointer(APackedData), FPackedSize);
  {$ELSE}
    CompressBuf(Data, Size, Pointer(APackedData), FPackedSize);
  {$ENDIF}
    try
      Dec(FPackedSize, ZLibFooterSize);
      Dec(FPackedSize, ZLibHeaderSize);
      DoWriteData(AStream, PByte(TdxNativeUInt(APackedData) + ZLibHeaderSize));
    finally
      FreeMem(APackedData);
    end;
  end
  else
  begin
    FCRC32 := 0;
    FPackedSize := 0;
    DoWriteData(AStream, nil);
  end;
end;

function TdxZIPItem.CheckName(const AName: AnsiString): AnsiString;
begin
  Result := TdxZIPPathHelper.ExcludeRootPathDelimiter(TdxZIPPathHelper.EncodePath(AName));
end;

function TdxZIPItem.GetData: PByte;
begin
  if not FDataAssigned then
  begin
    ReadData(FOwner.Stream);
    FDataAssigned := True;
  end;
  Result := FData;
end;

function TdxZIPItem.GetIsDirectory: Boolean;
begin
  Result := FAttributes and faDirectory = faDirectory;
end;

function TdxZIPItem.GetName: AnsiString;
begin
  if not FNameAssigned then
  begin
    ReadFileName(FOwner.Stream);
    FNameAssigned := True;
  end;
  Result := FName;
end;

procedure TdxZIPItem.ReadData(AStream: TStream);
var
  AFileData: TdxZIPFileEntry;
begin
  ReadFileEntryData(AStream, AFileData);
  AStream.Seek(AFileData.NameLength, soCurrent);
  if FPackedSize > 0 then
  begin
    GetMem(FData, Size);
    AStream.Seek(AFileData.ExtraLength, soCurrent);
    TdxZIPUnpackHelper.Unpack(AFileData.Method, FData, Size, AStream, FPackedSize);
    CheckRead((FCRC32 = 0) or (FCRC32 = dxCRC32(FData, Size)), dxAnsiStringToString(FName) + ' is corrupted.');
  end;
end;

procedure TdxZIPItem.ReadFileEntryData(AStream: TStream; var AData: TdxZIPFileEntry);
begin
  AStream.Position := FRelativeOffset;
  AStream.Read(AData, SizeOf(AData));

  CheckRead(FileHeader = AData.Sign);
  CheckRead((FSize = AData.OriginalSize) or (AData.OriginalSize = 0));
  CheckRead((FPackedSize = AData.PackedSize) or (AData.PackedSize = 0));
end;

procedure TdxZIPItem.ReadFileName(AStream: TStream);
var
  AFileData: TdxZIPFileEntry;
begin
  ReadFileEntryData(AStream, AFileData);
  SetLength(FName, AFileData.NameLength);
  if AFileData.NameLength > 0 then
  begin
    AStream.ReadBuffer(FName[1], AFileData.NameLength);
    FName := CheckName(FName);
  end;
end;

{ TdxZIPUnpackHelper }

class procedure TdxZIPUnpackHelper.Unpack(ACompressMethod: Word;
  ATargetBuffer: PByte; ATargetBufferSize: Integer; ASource: TStream; ASourceSize: Integer);
begin
  case ACompressMethod of
    0: UnpackNone(ATargetBuffer, ATargetBufferSize, ASource, ASourceSize);
    8: UnpackDeflate(ATargetBuffer, ATargetBufferSize, ASource, ASourceSize);
  else
    raise EdxZIPUnsupportedCompressionMethod.Create('');
  end;
end;

class procedure TdxZIPUnpackHelper.UnpackDeflate(
  ATargetBuffer: PByte; ATargetBufferSize: Integer; ASource: TStream; ASourceSize: Integer);
var
  P: PWordArray;
  ZRec: TZStreamRec;
begin
  ZeroMemory(@ZRec, SizeOf(ZRec));
  ZRec.zalloc := zlibAllocMem;
  ZRec.zfree := zlibFreeMem;

  GetMem(P, ASourceSize + ZLibHeaderSize);
  try
    P^[0] := ZLibVersion;
    ASource.ReadBuffer(P^[1], ASourceSize);
    ZRec.next_out := @ATargetBuffer^;
    ZRec.avail_out := ATargetBufferSize;
    ZRec.next_in := @P^[0];
    ZRec.avail_in := ASourceSize + ZLibHeaderSize;
    try
      CheckRead(InflateInit_(ZRec, ZLIB_VERSION, SizeOf(ZRec)) >= 0);
      while ZRec.avail_out > 0 do
        CheckRead(Inflate(ZRec, 0) >= 0);
    finally
      InflateEnd(ZRec);
    end;
  finally
    FreeMem(P);
  end;
end;

class procedure TdxZIPUnpackHelper.UnpackNone(
  ATargetBuffer: PByte; ATargetBufferSize: Integer; ASource: TStream; ASourceSize: Integer);
begin
  ASource.ReadBuffer(ATargetBuffer^, ATargetBufferSize);
end;

{ TdxZIPCustomStream }

constructor TdxZIPCustomStream.Create(const AFileName: string);
begin
  Create(TFileStream.Create(AFileName, fmOpenReadWrite), True);
end;

constructor TdxZIPCustomStream.Create(AStream: TStream; AAutoFreeStream: Boolean = False);
begin
  inherited Create;
  FStream := AStream;
  FAutoFreeStream := AAutoFreeStream;
  FItems := TcxObjectList.Create;
  ReadItems;
end;

destructor TdxZIPCustomStream.Destroy;
begin
  WriteItems;
  if FAutoFreeStream then
    FreeAndNil(FStream);
  FreeAndNil(FItems);
  inherited Destroy;
end;

function TdxZIPCustomStream.Add: TdxZIPItem;
begin
  Result := TdxZIPItem.Create(Self);
  FItems.Add(Result);
end;

procedure TdxZIPCustomStream.ReadItems;
begin
  // do nothing
end;

procedure TdxZIPCustomStream.WriteItems;
begin
  // do nothing
end;

function TdxZIPCustomStream.GetCount: Integer;
begin
  Result := FItems.Count;
end;

function TdxZIPCustomStream.GetItem(Index: Integer): TdxZIPItem;
begin
  Result := TdxZIPItem(FItems[Index]);
end;

{ TdxZIPStreamReader }

function TdxZIPStreamReader.Exists(const AFileName: AnsiString): Boolean;
var
  AItem: TdxZIPItem;
begin
  Result := Find(AFileName, AItem)
end;

function TdxZIPStreamReader.Find(AFileName: AnsiString; out AItem: TdxZIPItem): Boolean;
var
  I: Integer;
begin
  Result := False;
  AFileName := TdxZIPPathHelper.ExcludeRootPathDelimiter(AFileName);
  for I := 0 to Count - 1 do
    if SameText(Items[I].Name, AFileName) then
    begin
      AItem := Items[I];
      Result := True;
      Break;
    end;
end;

procedure TdxZIPStreamReader.ReadItems;
var
  I: Integer;
  ADirData: TdxZIPCentralDirEntry;
  AEndOfDir: TdxZIPEndOfDir;
begin
  Stream.Position := 0;
  Stream.ReadBuffer(ADirData, SizeOf(ADirData));
  if ADirData.Sign = FileHeader then
  begin
    Stream.Position := Stream.Size;
    repeat
      Stream.Seek(-SizeOf(TdxZIPEndOfDir), soCurrent);
      Stream.ReadBuffer(AEndOfDir, SizeOf(AEndOfDir));
      Stream.Seek(-1, soCurrent);
    until (AEndOfDir.Sign = EndOfDir) or (Stream.Position < SizeOf(AEndOfDir));
    CheckRead(AEndOfDir.Sign = EndOfDir);

    Stream.Position := AEndOfDir.DirOffset;
    for I := 0 to AEndOfDir.DirEntryCount - 1 do
    begin
      Stream.ReadBuffer(ADirData, SizeOf(ADirData));
      CheckRead(ADirData.Sign = DirFileHeader);
      Add.Initialize(ADirData);
      Stream.Seek(ADirData.NameLength + ADirData.ExtraLength + ADirData.CommentLength, soCurrent);
    end;
  end;
end;

{ TdxZIPStreamWriter }

constructor TdxZIPStreamWriter.Create(const AFileName: string);
begin
  Create(TFileStream.Create(AFileName, fmCreate), True);
end;

procedure TdxZIPStreamWriter.AddDirectory(const APath, ARelativeDir: AnsiString);
begin
  Add.Initialize(APath, nil);
end;

procedure TdxZIPStreamWriter.AddFile(const AFileName, ARelativeDir: AnsiString; AStream: TStream);
begin
  Add.Initialize(AFileName, AStream);
end;

procedure TdxZIPStreamWriter.AddFile(const AFileName, ARelativeDir: AnsiString; AData: PByte; ADataSize: Integer);
begin
  Add.Initialize(AFileName, AData, ADataSize);
end;

procedure TdxZIPStreamWriter.WriteCentralDirectory;
var
  ADirData: TdxZIPCentralDirEntry;
  AEndOfDir: TdxZIPEndOfDir;
  AItem: TdxZIPItem;
  I: Integer;
begin
  FillChar(AEndOfDir, SizeOf(AEndOfDir), 0);
  FillChar(ADirData, SizeOf(ADirData), 0);
  AEndOfDir.Sign := EndOfDir;
  AEndOfDir.DirOffset := Stream.Size;
  ADirData.Sign := DirFileHeader;
  ADirData.Version := 20;
  ADirData.VersionToExtract := 20;
  ADirData.Method := 8;

  for I := 0 to Count - 1 do
  begin
    AItem := Items[I];
    ADirData.CRC32 := AItem.FCRC32;
    ADirData.PackedSize := AItem.FPackedSize;
    ADirData.OriginalSize := AItem.Size;
    ADirData.ExtAttributes := AItem.FAttributes;
    ADirData.DateTime := AItem.DateTime;
    ADirData.NameLength := Length(AItem.Name);
    ADirData.RelativeOffset := AItem.FRelativeOffset;
    Stream.WriteBuffer(ADirData, SizeOf(ADirData));
    Stream.WriteBuffer(AItem.Name[1], ADirData.NameLength);
    Inc(AEndOfDir.DirEntryCount);
  end;
  AEndOfDir.DirStart := AEndOfDir.DirEntryCount;
  AEndOfDir.DirSize := Stream.Position - AEndOfDir.DirOffset;
  Stream.Write(AEndOfDir, SizeOf(AEndOfDir));
end;

procedure TdxZIPStreamWriter.WriteItems;
var
  I: Integer;
begin
  for I := 0 to Count - 1 do
    Items[I].WriteData(Stream);
  WriteCentralDirectory;
end;

{ TdxZIPPathHelper }

class function TdxZIPPathHelper.DecodePath(const APath: AnsiString): AnsiString;
begin
  Result := dxAnsiStringReplace(APath, '/', PathDelim, [rfReplaceAll]);
end;

class function TdxZIPPathHelper.EncodePath(const APath: AnsiString): AnsiString;
begin
  Result := dxAnsiStringReplace(APath, PathDelim, '/', [rfReplaceAll]);
end;

class function TdxZIPPathHelper.ExcludeRootPathDelimiter(const APath: AnsiString): AnsiString;
begin
  Result := APath;
  if (Length(Result) > 0) and (Result[1] = '/') then
    Delete(Result, 1, 1);
end;

end.
